Java 2D数组字符串或字符管理
我在java中使用数组进行赋值,这里有一些关于如何编写程序的说明。 我在步骤2中遇到的问题是如何初始化数组以显示如下输出(1A B C D)强>
为座位安排编写java程序。该程序应具有以下内容
1/要求用户输入座位安排中的行数(完成)
2/根据输入的行,使用数组和循环分配初始座位 编号和显示如下:
Example if you enter ----- > row = 3
The display will be:
1 A B C D
2 A B C D
3 A B C D
3/要求用户选择他们想要的座位,并为所选座位指定“X”。(已完成) 将要求用户输入,直到给出停止输入的sentinel值
4/在指定的“X”值后显示座椅模式
Example if the user choose ----- > 1A 2B 3D
The display will be:
1 X B C D
2 A X C D
3 A B C X
我编写了代码,但在一个问题中,我遇到了2D数组的问题,我不知道如何初始化数组它是字符串还是字符数组强>
我的代码
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter how many row in seating arrangment: ");
int rowNo = s.nextInt();
String seating[][] = new String[rowNo][4];
for (int i = 0; i < rowNo; i++) {
for (int j = 0; j < 4; j++) {
if (j == 0)
seating[i][j] = "A";
else if (j == 1)
seating[i][j] = "B";
else if (j == 2)
seating[i][j] = "C";
else
seating[i][j] = "D";
}
}
for (int i = 0; i < rowNo; i++) {
System.out.println(i + 1);
for (int j = 0; j < 4; j++) {
System.out.println((j + 1) + "\t" + seating[i][j]);
}
System.out.println();
}
String askUser = "Y";
while (askUser.equalsIgnoreCase("Y")) {
System.out.println("Chose your Seat ");
System.out.println("Enter the row ");
int row = s.nextInt();
System.out.println("Enter the column ");
String col = s.nextLine();
if (col.equals("A"))
seating[row - 1][0] = "X";
else if (col.equals("B"))
seating[row - 1][1] = "X";
else if (col.equals("C"))
seating[row - 1][2] = "X";
else
seating[row - 1][3] = "X";
System.out.println("Contnioe to choose seat [y -Yes | n-No] :");
askUser = s.next();
}
System.out.println("Find Seating");
for (int i = 0; i < rowNo; i++) {
for (int j = 0; j < 4; j++) {
System.out.println((j + 1) + "\t" + seating[i][j]);
}
System.out.println();
}
}
}
我的代码的输出
Enter how many row in seating arrangment:
3
1
1 A
2 B
3 C
4 D
2
1 A
2 B
3 C
4 D
Chose your Seat
Enter the row
2
Enter the column
A
Contnioe to choose seat [y -Yes | n-No] :
Find Seating
1 A
2 B
3 C
4 D
1 A
2 B
3 C
4 X
我的代码有什么错误? 老师提示:行号应该存储在一维字符串数组中。 字符应使用2D数组强>
我在寻求帮助。 问候
但是2d数组如果我这样做是正确的吗
String seatRow[]= new String[rowNo];
char [] col= {'A','B','C','D'};
//String[] col= {"a b c d "};
String s=Arrays.toString(col);
String SeatAval[][]= new String [rowNo][s.length()];
我对老师在字符串数组中设置行提供的提示感到困惑。和人物
# 1 楼答案
我已经编辑了你的代码,并添加了注释,这样你就知道出了什么问题。请阅读并理解。此外,您可能还应该添加一些错误检查,以防用户输入错误。以下是更新后的代码: